<template>
    <div class="user-manage">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
            <div class="item-group">
                <el-form-item label="募捐项目ID:">
                    <el-input v-model="searchForm.fundraisingProjectsId" placeholder="请输入募捐项目ID" />
                </el-form-item>
                <el-form-item label="募捐项目名称:">
                    <el-input v-model="searchForm.fundraisingProjectsName" placeholder="请输入募捐项目名称" />
                </el-form-item>
                <el-form-item label="募捐机构ID:">
                    <el-input v-model="searchForm.agencyId" placeholder="请输入募捐机构ID" />
                </el-form-item>
                <el-form-item label="募捐机构名称:">
                    <el-input v-model="searchForm.agencyName" placeholder="请输入募捐机构名称" />
                </el-form-item>
                <el-form-item label="募捐项目类型:">
                    <el-select v-model="searchForm.fundraisingProjectsType" placeholder="请选择募捐项目类型" style="width: 170px;" clearable>
                        <el-option v-for="item in fundraisingTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="募捐起止日期:">
                    <el-date-picker
                        v-model="searchForm.fundraisingProjectsTime"
                        type="daterange"
                        range-separator="~"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    />
                </el-form-item>
            </div>
            <div class="btn-group">
                <el-button type="primary" @click="getFundraisingProjectsList" size="small">
                    <el-icon><Search /></el-icon>
                    搜索
                </el-button>
                <el-button type="success" @click="handleEdit(1)" size="small">
                    <el-icon><Plus /></el-icon>
                    新增
                </el-button>
                <el-button type="danger" @click="handleDelete('batch')" size="small">
                    <el-icon><Minus /></el-icon>
                    批量删除
                </el-button>
            </div>
        </el-form>
        <!-- 表格数据 -->
        <el-table 
            :data="tableData" 
            style="width: 100%" 
            border 
            :header-cell-style="{ background: 'rgb(216,231,246)' }" 
            max-height="500"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="fundraisingProjectsId" label="募捐项目ID" width="100" />
            <el-table-column prop="fundraisingProjectsName" label="募捐项目名称" width="150" />
            <el-table-column prop="fundraisingProjectsPhoto" label="募捐项目图片" width="110">
                <template #default="scope">
                    <el-image :src="imageUrl + scope.row.fundraisingProjectsPhoto" style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column prop="agencyId" label="所属募捐机构ID" width="130" />
            <el-table-column prop="agencyName" label="所属募捐机构名称" width="150" />
            <el-table-column prop="expectedFundraisingAmount" label="期望募捐金额" width="110" />
            <el-table-column prop="fundraisingProjectsType" label="募捐项目类型" width="110">
                <template #default="scope">
                    <el-tag :type="scope.row.fundraisingProjectsType === '教育助学' ? 'primary' : scope.row.fundraisingProjectsType === '扶危助困' ? 'danger' : scope.row.fundraisingProjectsType === '乡村振兴' ? 'warning' : 'success'">{{ scope.row.fundraisingProjectsType  }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="fundraisingProjectsIntroduction" label="募捐项目简介" width="200" />
            <el-table-column prop="fundraisingProjectsStartTime" label="募捐起始日期" :formatter="handleFormatDate" width="160" />
            <el-table-column prop="fundraisingProjectsEndTime" label="募捐结束日期" :formatter="handleFormatDate" width="160" />
            <el-table-column label="操作" fixed="right" width="110">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleEdit(0, row)">编辑</el-button>
                    <el-button link type="primary" @click="handleDelete('single', row.fundraisingProjectsId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next,jumper"
                :page-sizes="[10, 50, 100]"
                :total="total"
                v-model:page-size="pageSize"
                v-model:current-page="currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        <!-- 编辑募捐项目信息弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700">
            <FundraisingProjectsForm :dialogForm="dialogForm" :isAdmin="true" ref="children" />
            <template #footer>
                <el-button type="primary" @click="handleSure">确定</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { adminApi } from '../../api/app';
import { Plus, Search, Minus } from '@element-plus/icons-vue'
import { imageUrl } from '../../api/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fundraisingTypeOptions, handleFormatDate } from './ts/common';
import { dayjs } from 'element-plus';
import FundraisingProjectsForm from './FundraisingProjectsForm.vue';
  
/** 搜索表单 */
const searchForm = ref({
    fundraisingProjectsId: null,
    fundraisingProjectsName: null,
    agencyId: null,
    agencyName: null,
    fundraisingProjectsType: null,
    fundraisingProjectsStartTime: null,
    fundraisingProjectsEndTime: null,
    fundraisingProjectsTime: null
})
/** 表格数据 */
const tableData = ref([])
/** 数据总数 */
const total = ref(0);
/** 当前页码 */
const currentPage = ref(1);
/** 每页显示条数 */
const pageSize = ref(10);
/** 多选选中内容 */
const selection = ref<any[]>([]);
/** 编辑募捐项目信息弹窗可见性 */
const dialogVisible = ref(false);
/** 编辑 | 新增弹窗标题 */
const dialogTitle = ref('');
/** 编辑 | 新增弹窗表单 */
const dialogForm = ref({
    fundraisingProjectsId: null,
    fundraisingProjectsName: null,
    fundraisingProjectsIntroduction: null,
    fundraisingProjectsPhoto: null,
    fundraisingProjectsStartTime: null,
    fundraisingProjectsEndTime: null,
    fundraisingProjectsType: null,
    fundraisingProjectsStatus: 1, // 管理员添加默认已审核
    agencyId: null,
    expectedFundraisingAmount: null,
    fundraisingProjectsContent: null,
});
const children = ref<any>(null);
  
// 初始加载
onMounted(() => {
    // 获取募捐项目列表
    getFundraisingProjectsList();
});
  
/** 获取募捐项目信息列表 */
const getFundraisingProjectsList = () => {
    const startTime = searchForm.value.fundraisingProjectsTime ? dayjs(searchForm.value.fundraisingProjectsTime?.[0]).format('YYYY-MM-DD') : null;
    const endTime = searchForm.value.fundraisingProjectsTime ? dayjs(searchForm.value.fundraisingProjectsTime?.[1]).format('YYYY-MM-DD') : null;
    adminApi.getFundraisingProjects({ 
        pageNum: currentPage.value, 
        pageSize: pageSize.value,
        ...searchForm.value,
        fundraisingProjectsStartTime: startTime,
        fundraisingProjectsEndTime: endTime,
        fundraisingProjectsTime: undefined
    }).then((res: any) => {
        if (res) {
            tableData.value = res.records;
            total.value = res.total;
        }
    });
};
  
/** 多选变化 */
const handleSelectionChange = (val: any) => {
    val.forEach((element: any) => selection.value.push(element.fundraisingProjectsId));
};
  
/** 新增 | 编辑募捐项目信息 */
const handleEdit = (type: number, row?: any) => {
    dialogVisible.value = true;
    dialogTitle.value = '新增募捐项目';
    resetForm();
    // 编辑模式 需要给表单赋值当前行数据
    if (type === 0) {
        dialogTitle.value = '编辑募捐项目信息';
        dialogForm.value = {
            ...row
        };
    };
}

/** 重置弹窗表单内容 */
const resetForm = () => {
    dialogForm.value = {
        fundraisingProjectsId: null,
        fundraisingProjectsName: null,
        fundraisingProjectsIntroduction: null,
        fundraisingProjectsPhoto: null,
        fundraisingProjectsStartTime: null,
        fundraisingProjectsEndTime: null,
        fundraisingProjectsType: null,
        agencyId: null,
        expectedFundraisingAmount: null,
        fundraisingProjectsStatus: 1,
        fundraisingProjectsContent: null,
    };
}

/** 重置弹窗内容并关闭弹窗 */
const resetDialog = () => {
    resetForm();
    dialogVisible.value = false;
    getFundraisingProjectsList();
};
  
/** 弹窗确定 */
const handleSure = () => {
    if (children.value) {
        dialogForm.value.fundraisingProjectsContent = children.value.getEditorHTML();
    }
    const endTime = dialogForm.value.fundraisingProjectsEndTime ? dayjs(dialogForm.value.fundraisingProjectsEndTime).format('YYYY-MM-DD') : null;
    const projects = {
        ...dialogForm.value,
        fundraisingProjectsEndTime: endTime
    };
    if (dialogTitle.value === '新增募捐项目') {
        adminApi.addFundraisingProject(projects).then(res => {
            if (res) {
                ElMessage.success('新增成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('新增失败');
        });
    } else {
        adminApi.updateFundraisingProject(projects).then(res => {
            if (res) {
                ElMessage.success('编辑成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('编辑失败');
        });
    }
};
  
/** 删除募捐项目 */
const handleDelete = (control: string, fundraisingProjectsId?: string) => {
    ElMessageBox.confirm('确定删除吗？', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const fundraisingProjectsIds = control === 'single' ? [fundraisingProjectsId] : selection.value;
        adminApi.deleteFundraisingProjects(fundraisingProjectsIds).then(res => {
            if (res) {
                ElMessage.success('删除成功');
                getFundraisingProjectsList();
                // 批量删除清空选中内容
                if(control === 'batch') {
                    selection.value = [];
                }
            } else {
                ElMessage.error('删除失败');
            }
        });
    }).catch(() => {
        ElMessage.info('已取消');
    });
  }
  
/** 表格分页大小改变 */
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getFundraisingProjectsList();
}
  
/** 表格页码改变 */
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getFundraisingProjectsList();
};
</script>
  
<style scoped lang="less">
@import "./css/tableForm.less";
</style>